package net.csdn.business.common.utils;

import cn.hutool.core.util.RandomUtil;
import net.sourceforge.pinyin4j.PinyinHelper;
import net.sourceforge.pinyin4j.format.HanyuPinyinCaseType;
import net.sourceforge.pinyin4j.format.HanyuPinyinOutputFormat;
import net.sourceforge.pinyin4j.format.HanyuPinyinToneType;
import net.sourceforge.pinyin4j.format.exception.BadHanyuPinyinOutputFormatCombination;


/**
 * @program: openatom
 * @description: 拼音转汉字工具类
 * @author: zhangyl
 * @create: 2024-07-30 10:44
 **/
public class PinyinConverter {



    public static String convertToPinyin(String chinese) {
        HanyuPinyinOutputFormat format = new HanyuPinyinOutputFormat();
        format.setCaseType(HanyuPinyinCaseType.LOWERCASE);
        format.setToneType(HanyuPinyinToneType.WITHOUT_TONE);

        StringBuilder pinyinBuilder = new StringBuilder();
        char[] chars = chinese.toCharArray();
        for (char c : chars) {
            if((c>='a'&&c<='z') || (c>='A'&&c<='Z')||Character.isDigit(c)){
                pinyinBuilder.append(c);
            } else {
                try {
                    String[] pinyinArray = PinyinHelper.toHanyuPinyinStringArray(c, format);
                    if (pinyinArray != null&&pinyinArray.length > 0) {
                        pinyinBuilder.append(pinyinArray[0]);
                    }
                } catch (BadHanyuPinyinOutputFormatCombination e) {
                    e.printStackTrace();
                }
            }
        }
        if(pinyinBuilder.length()==0){
            String randomStr=RandomUtil.randomString("abcdefghijklmnopqrstuvwxyz", 6);
            pinyinBuilder.append("user_").append(randomStr);
            return pinyinBuilder.toString();
        }else{
            //此处replace是针对如：仙女不讲李 这样含有女的昵称，转换后出现":".
            return pinyinBuilder.toString().replace(":","").toLowerCase();
        }
    }

    public static void main(String[] args) {
        String chineseWithPunctuation = "仙女不讲李";
        String pinyin = convertToPinyin(chineseWithPunctuation);
        System.out.println(pinyin); // 输出: nihongshijie
    }
}
